package me.jiatao.wan.common

import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.tencent.mmkv.MMKV
import me.jiatao.wan.common.ext.fromJson
import me.jiatao.wan.common.ext.typedToJson
import me.jiatao.wan.init.AppHelper
import me.jiatao.wan.model.UserInfoModel
import okhttp3.Cookie
import timber.log.Timber

/**
 * @Author: taojia
 * @CreateDate: 2021/9/9 2:19 下午
 * @Version: 1.0
 * @Description:
 */

/**
 * MMKV保存对象
 */
inline fun <reified T> MMKV.encodeObj(key: String, data: T): Boolean {
    val json = Gson().typedToJson(data)
    return encode(key, json)
}

/**
 * MMKV加载对象
 */
inline fun <reified T> MMKV.decodeObj(key: String): T? {
    val json = decodeString(key, "")
    return if (json.isNullOrEmpty()) {
        null
    } else {
        Gson().fromJson(json)
    }
}


object LocalStorage {
    private const val USER_KEY: String = "USER_KEY"
    private val mmkv: MMKV by lazy { MMKV.defaultMMKV() }


    init {
        val rootDir: String = MMKV.initialize(AppHelper.mContext)
        Timber.d("mmkv root: $rootDir")
    }

    /**
     * 保存cookie
     */
    fun saveCookie(urlString: String, cookies: List<Cookie>): Boolean {
        return mmkv.encodeObj(urlString, cookies)
    }

    /**
     * 读取本地cookie
     */
    fun loadCookie(urlString: String): List<Cookie> {
        return mmkv.decodeObj<List<Cookie>>(urlString) ?: emptyList()
    }

    /**
     * 保存用户昵称
     */
    fun saveUserName(userName: String) {
        mmkv.encode(USER_KEY, userName)
    }

    /**
     * 记载用户昵称
     */
    fun loadUser(): UserInfoModel {
        val userName = mmkv.decodeString(USER_KEY, "")
        val userInfo = UserInfoModel()
        if (!userName.isNullOrEmpty()) {
            userInfo.setUserName(userName)
        }
        return userInfo
    }

    /**
     * 返回用户是否登录
     */
    fun hasUserLogin(): Boolean {
        return mmkv.containsKey(USER_KEY)
    }

    /**
     * 用户登出
     */
    fun logout() {
        mmkv.clearAll()
    }
}